package com.hdoit.ares.logical.cust.service.impl;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import javax.annotation.Resource;

import me.chanjar.weixin.mp.bean.result.WxMpUser;

import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import com.hdoit.ares.logical.acc.service.IAccountInfoService;
import com.hdoit.ares.logical.acc.service.IGoldenBeanInfoService;
import com.hdoit.ares.logical.acc.service.IIncomeInfoService;
import com.hdoit.ares.logical.acti.service.ITaskGoldenBeanService;
import com.hdoit.ares.logical.cust.dao.ICustomerDao;
import com.hdoit.ares.logical.cust.model.Customer;
import com.hdoit.ares.logical.cust.service.ICustomerService;
import com.hdoit.ares.logical.viewmodel.cust.CustomerColumn;
import com.hdoit.ares.logical.viewmodel.cust.CustomerSearch;
import com.hdoit.ares.logical.viewmodel.cust.CustomerStatistic;
import com.hdoit.ares.logical.viewmodel.cust.CustomerTree;
import com.hdoit.ares.logical.viewmodel.cust.TeamShareCustomer;
import com.hdoit.ares.selfcommon.enums.cust.AttentionStatus;
import com.hdoit.ares.selfcommon.enums.cust.CustomerLevel;
import com.tennetcn.common.dao.base.impl.SuperService;
import com.tennetcn.common.enums.pub.YesOrNo;
import com.tennetcn.common.message.DaoBaseRuntimeException;
import com.tennetcn.common.message.PagerModel;
import com.tennetcn.common.utils.ChineseUtils;
import com.tennetcn.common.utils.CommonUtils;
import com.tennetcn.common.utils.DateUtils;

/**
 * @author chenghuan
 * @email
 * @createtime 2017年10月26日 16:26:52
 * @comment
 */
@Component
public class CustomerServiceImpl extends SuperService<Customer> implements ICustomerService {
	
	public final static String StrAccountNo = "yyyyMMddHHmmss";
	
	private IGoldenBeanInfoService goldenBeanInfoService;
	
	public IGoldenBeanInfoService getGoldenBeanInfoService() {
		return goldenBeanInfoService;
	}
	@Resource
	public void setGoldenBeanInfoService(IGoldenBeanInfoService goldenBeanInfoService) {
		this.goldenBeanInfoService = goldenBeanInfoService;
	}

	private IAccountInfoService accountInfoService;

	public IAccountInfoService AccountInfoService() {
		return accountInfoService;
	}

	@Resource
	public void setAccountInfoService(IAccountInfoService accountInfoService) {
		this.accountInfoService = accountInfoService;
	}
	
	private IIncomeInfoService incomeInfoService;
	
	public IIncomeInfoService getIncomeInfoService() {
		return incomeInfoService;
	}
	
	@Resource
	public void setIncomeInfoService(IIncomeInfoService incomeInfoService) {
		this.incomeInfoService = incomeInfoService;
	}

	private ICustomerDao customerDao;

	public ICustomerDao getCustomerDao() {
		return customerDao;
	}

	@Resource
	public void setCustomerDao(ICustomerDao customerDao) {
		this.customerDao = customerDao;
	}
	
	private ITaskGoldenBeanService taskGoldenBeanService;
	public ITaskGoldenBeanService getTaskGoldenBeanService() {
		return taskGoldenBeanService;
	}
	@Resource
	public void setTaskGoldenBeanService(ITaskGoldenBeanService taskGoldenBeanService) {
		this.taskGoldenBeanService = taskGoldenBeanService;
	}
	@Override
	public Customer queryModelByUserIdentity(int userIdentity) {
		return customerDao.queryModelByUserIdentity(userIdentity);
	}

	@Override
	public String queryIdByUserIdentity(int userIdentity) {
		return customerDao.queryIdByUserIdentity(userIdentity);
	}

	@Override
	public int queryMaxUserIdentity() {
		return customerDao.queryMaxUserIdentity();
	}

	@Override
	public Customer queryModelByOpenId(String openId) {
		return customerDao.queryModelByOpenId(openId);
	}
	
	@Override
	public Customer addCustomer(String openId, WxMpUser mpUser, int refereeIdentity) {
		Customer customer = new Customer();
		customer.setId(CommonUtils.getKeyId());
		customer.setOpenId(openId);
		customer.setLevel(CustomerLevel.visitor);
		customer.setAutonym(YesOrNo.no);
		customer.setAttentionDate(DateUtils.getCurrent());
		customer.setAttentionStatus(AttentionStatus.attention);
		customer.setRegistDate(DateUtils.getCurrent());
		if(refereeIdentity==-1){
			customer.setAttentionStatus(AttentionStatus.cancelAttention);
			customer.setCancelAttentionDate(DateUtils.getCurrent());
		}
		if (refereeIdentity > 0) {
			Customer refreCustomer = queryModelByUserIdentity(refereeIdentity);		
			if (!StringUtils.isEmpty(refreCustomer)) {
				customer.setRefereeIdentity(refereeIdentity);
				customer.setRefereeId(refreCustomer.getId());
				customer.setRegion(refreCustomer.getRegion());
				customer.setUpdateRegionDate(DateUtils.getCurrent());
			}
		}
		int userIdentity = queryMaxUserIdentity();
		if (userIdentity < 2000) {
			userIdentity = 2000;
		}
		userIdentity++;
		customer.setUserIdentity(userIdentity);

		String sex="女".equals(mpUser.getSex())?"2":"1";
		customer.setSex(sex);
		//替换emoji表情
		customer.setNickname(ChineseUtils.replaceEmoji(mpUser.getNickname()));
		//customer.setNickname(mpUser.getNickname());
		customer.setPicPath(mpUser.getHeadImgUrl());
		customer.setUnionId(mpUser.getUnionId());

		if(addModel(customer)){
			if(!accountInfoService.addAccountInfo(customer)){
				//添加账户失败，抛出运行时异常
				throw new DaoBaseRuntimeException("CustomerServiceImpl.addCustomer.addAccount failed" + "添加账户失败");
			};
			if(!goldenBeanInfoService.addGoldenBeanInfo(customer)){
				//添加账户金豆表失败，抛出运行时异常
				throw new DaoBaseRuntimeException("CustomerServiceImpl.addCustomer.addGoldenBeanInfo failed" + "添加金豆账户失败");
			};
			if(!incomeInfoService.addIncomeInfo(customer)){
				//添加账户奖金表失败，抛出运行时异常
				throw new DaoBaseRuntimeException("CustomerServiceImpl.addCustomer.addIncomeInfo failed" + "添加奖金账户失败");
			};
			if(!taskGoldenBeanService.addTaskGoldenBean(customer)){
				//添加任务金豆表失败，抛出运行时异常
				throw new DaoBaseRuntimeException("CustomerServiceImpl.addCustomer.addTaskGoldenBean failed" + "添加任务金豆失败");
			};
			return customer;
		}
		return null;
	}

	@Override
	public int queryInviteSum(String id) {
		return customerDao.queryInviteSum(id);
	}

	@Override
	public boolean updateRegister(Customer customer) {
		return customerDao.updateRegister(customer);
	}

	@Override
	public List<TeamShareCustomer> queryOneTeamShare(String id) {
		return customerDao.queryOneTeamShare(id);
	}

	@Override
	public List<TeamShareCustomer> queryTwoTeamShare(String id) {
		return customerDao.queryTwoTeamShare(id);
	}

	@Override
	public List<Customer> queryCurrentChildCustomer(String id) {
		return customerDao.queryCurrentChildCustomer(id);
	}

	@Override
	public int queryOneTeamShareCount(String id) {
		return customerDao.queryOneTeamShareCount(id);
	}

	@Override
	public int queryTwoTeamShareCount(String id) {
		return customerDao.queryTwoTeamShareCount(id);
	}

	@Override
	public List<Customer> queryListMP(CustomerSearch customerSearch,
			PagerModel pagerModel) {
		return customerDao.queryListMP(customerSearch, pagerModel);
	}

	@Override
	public List<Customer> queryListMP(CustomerSearch customerSearch) {
		return customerDao.queryListMP(customerSearch);
	}

	@Override
	public int queryCountMP(CustomerSearch customerSearch) {
		return customerDao.queryCountMP(customerSearch);
	}
	
	@Override
	public Customer queryModelMP(String key) {
		return customerDao.queryModelMP(key);
	}
	
	@Override
	public List<Customer> queryListById(CustomerSearch customerSearch,
			PagerModel pagerModel,String key) {
		return customerDao.queryListById(customerSearch, pagerModel,key);
	}

	@Override
	public int queryCountById(CustomerSearch customerSearch,String key) {
		return customerDao.queryCountById(customerSearch,key);
	}

	public boolean updateMaker(String openId) {
		return customerDao.updateLevel(openId, CustomerLevel.maker);
	}

	@Override
	public boolean updateHighMaker(String openId) {
		return customerDao.updateLevel(openId, CustomerLevel.highMaker);
	}

	@Override
	public Customer queryRefereeModelByOpenId(String openId) {
		return customerDao.queryRefereeModelByOpenId(openId);
	}

//	@Override
//	public boolean updateLevelDetailed(String id, String level, String phone, String username, String region) {
//		return customerDao.updateLevelDetailed(id, level, phone, username, region);
//	}

	@Override
	public boolean queryPhoneExisted(String phone) {
		return customerDao.queryModelByPhone(phone)!=null;
	}

	@Override
	public Customer queryModelByPhone(String phone){		
		return customerDao.queryModelByPhone(phone);
	}
	
	@Override
	public boolean updateCustomerByJoinMaker(Customer customer){
		return customerDao.updateCustomerByJoinMaker(customer);
	}

	@Override
	public List<Customer> queryListByBuyer(String loginId) {
		return customerDao.queryListByBuyer(loginId);
	}

	@Override
	public boolean updateCustomerState(String loginId, String autonym,String username,
			String idType, String idCode) {
		return customerDao.updateCustomerState(loginId, autonym,username, idType, idCode);
	}

	@Override
	public boolean updateCustDetail(Customer customer) {
		
		if(customer.getBirthday()!=null){
			
			return customerDao.updateCustDetail("birthday",customer.getId(), customer.getBirthday());
		
		}else if (!StringUtils.isEmpty(customer.getRegion())) {	
			
			return customerDao.updateCustDetail("region",customer.getId(), customer.getRegion())
				&& customerDao.updateCustDetail("updateRegionDate",customer.getId(),DateUtils.getCurrent());
			
		}else if (!StringUtils.isEmpty(customer.getNickname())) {		
			
			return customerDao.updateCustDetail("nickname",customer.getId(), customer.getNickname());
						
		}else if (!StringUtils.isEmpty(customer.getEmail())) {
			
			return customerDao.updateCustDetail("email",customer.getId(), customer.getEmail());
			
		}
		return false;
	}

	@Override
	public Boolean updateCustomerStateById(String id, String state) {
		
		return customerDao.updateCustomerStateById(id, state);
	}
	@Override
	public List<TeamShareCustomer> queryWechatSearch(String searchContent, String id) {
		
		return customerDao.queryWechatSearch(searchContent, id);
	}
	
	@Override
	public List<Customer> queryListForAward(Date startDate, Date endDate) {
		
		return customerDao.queryListForAward(startDate, endDate);
	}
	
	
	@Override
	public HashMap<String,String> queryCustCount(String state,CustomerSearch search) {
		

		HashMap<String,String> map = new HashMap<String,String>();
		
		Calendar now = Calendar.getInstance();
		//获取当前时间
		now.setTime(DateUtils.getCurrent());
		//获取当前月份的天数
		int days = now.getActualMaximum(Calendar.DATE);
		
		for(int i = 1; i <= days; i++){
			map.put(String.valueOf(i),String.valueOf(0));
		}
		
		List<Customer> customers = customerDao.queryCountForStatistic("attentionDate",search);
	    
		
		for(Customer customer:customers){
	    	now.setTime(customer.getAttentionDate());
	    	String key = "" + now.get(Calendar.DAY_OF_MONTH);
	    	int value = Integer.valueOf(map.get(key)) + 1;
	    	map.replace(key, String.valueOf(value));
	    }
		
	    return map;
	}
	

	@Override
	public HashMap<String,String> queryAllCustCount(String state,CustomerSearch search) {
		
		HashMap<String,String> map = new HashMap<String,String>();
		
		Calendar now = Calendar.getInstance();
		//获取当前时间
		now.setTime(DateUtils.getCurrent());
		//获取当前月份的天数
		int days = now.getActualMaximum(Calendar.DATE);
		
		
		for(int i = 1; i <= days; i++){
			map.put(String.valueOf(i),String.valueOf(0));
		}
		
		List<Customer> customers = customerDao.queryCountForStatistic(state,search);
	    
		if("attentionDate".equals(state)){
			for(Customer customer:customers){
				now.setTime(customer.getAttentionDate());
				String key = "" + now.get(Calendar.DAY_OF_MONTH);
				int value = Integer.valueOf(map.get(key)) + 1;
				map.replace(key, String.valueOf(value));
			}
		}else if("joinMakerDate".equals(state)){
			for(Customer customer:customers){
				now.setTime(customer.getJoinMakerDate());
				String key = "" + now.get(Calendar.DAY_OF_MONTH);
				int value = Integer.valueOf(map.get(key)) + 1;
				map.replace(key, String.valueOf(value));
			}
		}else if("joinHighMakerDate".equals(state)){
			for(Customer customer:customers){
				now.setTime(customer.getJoinHighMakerDate());
				String key = "" + now.get(Calendar.DAY_OF_MONTH);
				int value = Integer.valueOf(map.get(key)) + 1;
				map.replace(key, String.valueOf(value));
			}	
		}
			
	    return map;
	}
	@Override
	public Boolean updatePassword(String newPassword, String customerId,String unionMark) {
		
		return customerDao.updatePassword(newPassword, customerId,unionMark);
	}
	
	
	
	@Override
	public List<CustomerTree> queryCustomerTreeList(CustomerSearch search) {
		List<CustomerTree> customerTrees = customerDao.queryTopList(search);
		if(customerTrees==null||customerTrees.size()<=0){
			return null;
		}
		
		List<CustomerTree> allCustomer = customerDao.queryTreeList();
		
		selCustomer(allCustomer,customerTrees);
		

		return customerTrees;
	}
	
	
	private void selCustomer(List<CustomerTree> allCustomer, List<CustomerTree> customerTrees) {
		if(customerTrees==null||customerTrees.size()==0){return;}
		int depth=1;
		for (CustomerTree  customerTree : customerTrees) {
			if(StringUtils.isEmpty(customerTree.getDepth())){
				customerTree.setDepth(""+depth);
				depth++;
			}
			if(StringUtils.isEmpty(customerTree.getUsername())){
				customerTree.setUsername(customerTree.getNickname());
			}
			List<CustomerTree> childCustomerTreeList=queryCustomerByRefreeId(allCustomer,customerTree);
			if(childCustomerTreeList == null || childCustomerTreeList.size() == 0){
				customerTree.setIcon("icon-user  text-grey-300");
			}else{
				customerTree.setIcon("icon-user-plus text-orange-700");
			}

			customerTree.setChildren(childCustomerTreeList);
			
			selCustomer(allCustomer,childCustomerTreeList);
		}
		
	}
	private List<CustomerTree> queryCustomerByRefreeId(List<CustomerTree> allCustomer,
			CustomerTree parent) {
		List<CustomerTree> childList=new ArrayList<CustomerTree>();
		int depth=1;
		for (CustomerTree childCustomerTree : allCustomer) {
			if(parent.getId().equals(childCustomerTree.getRefereeId())){
				childCustomerTree.setDepth(parent.getDepth()+"."+depth);
				childList.add(childCustomerTree);
				//统计一级游客，会员，初创，高创
				if(CustomerLevel.visitor.equals(childCustomerTree.getLevel())){
					parent.setFirstVisitor(parent.getFirstVisitor() + 1);
				}else if(CustomerLevel.vip.equals(childCustomerTree.getLevel())){
					parent.setFirstVip(parent.getFirstVip() + 1);
				}else if(CustomerLevel.maker.equals(childCustomerTree.getLevel())){
					parent.setFirstMaker(parent.getFirstMaker() + 1);
				}else if(CustomerLevel.highMaker.equals(childCustomerTree.getLevel())){
					parent.setFirstHighMaker(parent.getFirstHighMaker() + 1);
				}
				
				depth++;
			}
		}
		return childList;
	}
	
	@Override
	public CustomerTree queryModelForConsumption(CustomerSearch search) {
		CustomerTree customerTree = customerDao.queryModelForConsumption(search);
		 
		if(customerTree==null){
			return null;
		}
		List<CustomerTree> customerTrees = new ArrayList<CustomerTree>();
		customerTrees.add(customerTree);
		List<CustomerTree> allCustomer = customerDao.queryTreeList();
		
		selCustomer(allCustomer,customerTrees);
		

		return customerTrees.get(0);
	}
	
	@Override
	public List<CustomerTree> queryListForConsumption(CustomerSearch search) {
		List<CustomerTree> customerTrees =  customerDao.queryListForConsumption(search);
		if(customerTrees==null||customerTrees.size()<=0){
			return null;
		}
		
		List<CustomerTree> allCustomer = customerDao.queryTreeList();
		
		selCustomer(allCustomer,customerTrees);
		

		return customerTrees;
	}

	@Override
	public CustomerStatistic queryModel(CustomerSearch search) {
		return customerDao.queryModel(search);
	}
	
	
	 /*<----------------------------API------------------------->*/
	@Override
	public Customer login(String userId, String password) {
		
		return customerDao.login(userId, password);
	}
	@Override
	public Boolean queryUnionId(String unionId) {
		
		return customerDao.queryUnionId(unionId);
	}
	@Override
	public Customer queryModelByUnionId(String unionId) {
		
		return customerDao.queryModelByUnionId(unionId);
	}
	@Override
	public Customer queryModelByUnionIdOrPhone(String unionId, String phone) {
		
		return customerDao.queryModelByUnionIdOrPhone(unionId, phone);
	}
	
	@Override
	public boolean updateCustomerColumn(List<CustomerColumn> customerColumns) {
		System.err.println("customer的数量" + customerColumns.size());
		for(CustomerColumn customerColumn:customerColumns){
			updateReferee(customerColumn);
			if(!customerDao.updateCustomerColumn(customerColumn)){
				return false;
			}
		}
		return true;
	}
	
	/**
	 * 确认是否有上级：
	 * 1>如果有上一级则不修改其上一级
	 * 2>如果没有上一级则修改其上一级
	 */
	public CustomerColumn updateReferee(CustomerColumn customerColumn){
		Customer cus = customerDao.queryModelByUserIdentity(Integer.valueOf(customerColumn.getUserIdentity()));
		if(!StringUtils.isEmpty(customerColumn.getRefereeIdentity())){
			Customer refereeCus = customerDao.queryModelByUserIdentity(Integer.valueOf(customerColumn.getRefereeIdentity()));
			if(StringUtils.isEmpty(cus.getRefereeId())){
				customerColumn.setRefereeIdentity(String.valueOf(refereeCus.getRefereeIdentity()));
				customerColumn.setRefereeId(refereeCus.getRefereeId());
			}else{
				customerColumn.setRefereeIdentity(String.valueOf(cus.getRefereeIdentity()));
				customerColumn.setRefereeId(cus.getRefereeId());
			}
		}
		return customerColumn;
	}
	@Override
	public int queryCountDayMakers(String refereeId) {
		return customerDao.queryCountDayMakers(refereeId);
	}
	@Override
	public int queryCountWeekMakers(String refereeId) {
		return customerDao.queryCountWeekMakers(refereeId);
	}
	@Override
	public int queryCountMonthMakers(String refereeId) {
		return customerDao.queryCountMonthMakers(refereeId);
	}
	@Override
	public Boolean queryIsCountDayMaker(String refereeId) {
		if(customerDao.queryCountDayMakers(refereeId)>=1){
			return true;
		}
		return false;
	}
	@Override
	public Boolean queryIsCountWeekMaker(String refereeId) {
		if(customerDao.queryCountWeekMakers(refereeId)>=3){
			return true;
		}
		return false;
	}
	@Override
	public Boolean queryIsCountMonthMaker(String refereeId) {
		if(customerDao.queryCountMonthMakers(refereeId)>=10){
			return true;
		}
		return false;
	}
	@Override
	public List<Customer> queryNextVisitors(String refereeId) {
		return customerDao.queryNextVisitors(refereeId);
	}
}
